const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgUrl: app.globalData.imgUrl,
    allchecked: false,
    isEdit: false,
    goodsList: [{
        img: "https://xxx/uploads/ufa/gds/GoodsVO/2019/07/20/1Ni0DXD5SGyUYlUIjzsshw.jpeg",
        title: 'xxx…',
        price: 200
      },
    ],
    totalPrice:0,
    ordeGoodsrList:[]
  },

  //编辑
  handleEdit: function() {
    this.setData({
      isEdit: !this.data.isEdit
    })
  },

  //删除
  handleDel:function(e){
    var key = e.target.dataset.key;
    var goodslist = this.data.ordeGoodsrList 
    var newlist=goodslist.filter((item,index) => index!=key) 
    this.setData({
      ordeGoodsrList: newlist 
    })
    //数据小于0取消全选
    if (newlist.length<1){
      this.setData({
        allchecked: false
      })
    } 
    this.hendleTotalPrice()
  },

  // 全选
  onChange: function(e) {
    var goodslist = this.data.ordeGoodsrList
    goodslist.map((item, index) => {
      item.checked = !this.data.allchecked
    })
    this.setData({
      ordeGoodsrList: goodslist,
      allchecked: !this.data.allchecked
    })
    this.hendleTotalPrice()
  },


  //单选
  changeitem: function(e) {
    var key = e.target.dataset.key;
    var goodslist = this.data.ordeGoodsrList;
    var flag=false;
    var checkNum=0
    goodslist.map((item, index) => {
      if (index === key) {
        item.checked = !item.checked
      }
      if (item.checked === true){
        checkNum++
      } 
    })
    //判断选中个数是否与订单列表长度相等，
    if (checkNum==goodslist.length){
      flag=true
    }  
    this.setData({
      ordeGoodsrList: goodslist,
      allchecked: flag
    })
    this.hendleTotalPrice()
  },


  //监听购物车数量
  handleCart(e) {
    console.log(e)
    var num = e.detail
    var key = e.target.dataset.key;
    var goodslist = this.data.ordeGoodsrList
    goodslist.map((item, index) => {
      if (index === key) {
        item.num = num
      }
    })
    this.setData({
      ordeGoodsrList: goodslist
    })
    this.hendleTotalPrice()
  },


  hendleTotalPrice() { //计算总价
    let that = this
    let price = 0
    for (let i = 0; i < that.data.ordeGoodsrList.length; i++) {
      if (that.data.ordeGoodsrList[i].checked) {
        price = price + that.data.ordeGoodsrList[i].price * that.data.ordeGoodsrList[i].num
      }
    } 
    this.setData({
      totalPrice: price
    })

  },
  



})